package com.hospital.post.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {
    /**
     * 对象转JSON字符串
     * @param object 对象
     * @return JSON字符串
     */
    private static final ObjectMapper objectMapper = new ObjectMapper();
    public static String toJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("转JSON失败",e);
        }
    }

    /**
     * JSON字符串转对象
     * @param json 字符串
     * @param clazz 目标对象类
     * @return 对象
     */
    public static <T> T parse(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("转对象失败",e);
        }
    }

    /**
     * JSON字符串转对象
     * @param json 字符串
     * @param tr TypeReference
     * @return 对象
     */
    public static <T> T parse(String json, TypeReference<T> tr) {
        try {
            return objectMapper.readValue(json, tr);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("转对象失败",e);
        }
    }
}
